﻿using System;
using System.Linq;
using System.Windows.Forms;
using ExcelRefresh.Excel;

namespace ExcelRefreshUI
{
    public partial class ServiceConfig : Form
    {
        public ServiceConfig()
        {
            InitializeComponent();
        }

        private void btnAddFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                lbFolders.Items.Add(folderBrowserDialog1.SelectedPath);
        }

        private void lbFolders_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnRemoveFolder.Enabled = lbFolders.SelectedItem != null;
        }

        private void btnRemoveFolder_Click(object sender, EventArgs e)
        {
            lbFolders.Items.RemoveAt(lbFolders.SelectedIndex);
        }

        private void ServiceConfig_Load(object sender, EventArgs e)
        {
            lbFolders.Items.AddRange(Settings.FoldersToScan);
            updownThreads.Maximum = Environment.ProcessorCount * 2;
            updownThreads.Value = Settings.MaxThreads;
            tbRefreshTimeout.Text = Settings.RefreshTimeout.ToString();
            tbTargetFolder.Text = Settings.CopyRefreshedFilesToFolder;
        }

        private void bntOK_Click(object sender, EventArgs e)
        {
            Settings.FoldersToScan = lbFolders.Items.Cast<string>().ToArray();
            Settings.MaxThreads = Convert.ToInt32(updownThreads.Value);
            Settings.CopyRefreshedFilesToFolder = tbTargetFolder.Text;

            TimeSpan timespan;
            if(TimeSpan.TryParse(tbRefreshTimeout.Text, out timespan))
                Settings.RefreshTimeout = timespan;

            Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
